package cn.lxinet.lxms.system.service;

import cn.lxinet.lxms.framework.security.entity.LxmsUser;
import cn.lxinet.lxms.framework.security.service.LxmsUserDetailService;
import cn.lxinet.lxms.system.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统模块security登录用户权限查询
 *
 * @author zcx
 * @date 2023/07/19
 */
@Service
public class SystemUserDetailService implements LxmsUserDetailService {
    @Autowired
    @Lazy
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysMenuService sysMenuService;
    @Override
    public LxmsUser loadUserByUsername(String username) {
        SysUser sysUser = sysUserService.findByName(username);
        List<Long> roleIds = sysUserRoleService.queryRoleIds(sysUser.getId());
        boolean isAdministrator = sysUserRoleService.isAdministrator(sysUser.getId());
        List<String> permissionList = isAdministrator ? sysMenuService.listAllPermissions() : sysMenuService.listPermissionsByRoleIds(roleIds);
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        permissionList.forEach(permission -> grantedAuthorityList.add(() -> permission));
        return new LxmsUser(sysUser.getId(), sysUser.getName(), isAdministrator, grantedAuthorityList);
    }
}
